use std::collections::HashMap;
use std::fs;
use std::path::Path;
use regex::Regex;
use lazy_static::lazy_static;

fn get_st_map() -> HashMap<String, String> {
    // 读取 st.txt 文件，构建简体转繁体的映射表
    let project_root = env!("CARGO_MANIFEST_DIR");
    let file_path = Path::new(&project_root).join("st.txt");
    let mut st_map: HashMap<String, String> = HashMap::new();
    let content = fs::read_to_string(file_path).unwrap();
    for line in content.lines() {
        let words: Vec<&str> = line.split_whitespace().collect();
        if words.len() >= 2 {
            st_map.insert(words[0].to_string(), words[1].to_string());
        }
    }
    st_map
}

fn get_ts_map() -> HashMap<String, String> {
    // 读取 st.txt 文件，逆向构建繁体转简体的映射表
    let project_root = env!("CARGO_MANIFEST_DIR");
    let file_path = Path::new(&project_root).join("st.txt");
    let mut ts_map: HashMap<String, String> = HashMap::new();
    let content = fs::read_to_string(file_path).unwrap();
    for line in content.lines() {
        let words: Vec<&str> = line.split_whitespace().collect();
        if words.len() >= 2 {
            ts_map.insert(words[1].to_string(), words[0].to_string());
        }
    }
    ts_map
}

lazy_static! {
    static ref ST_MAP: HashMap<String, String> = get_st_map();
    static ref TS_MAP: HashMap<String, String> = get_ts_map();
}

enum ConverterType {
    Simple2Traditional, // 简体转繁体
    Traditional2Simple, // 繁体转简体
}

fn translate(input: &str, converter: ConverterType) -> String {
    let convert_map = match converter {
        ConverterType::Simple2Traditional => &*ST_MAP,
        ConverterType::Traditional2Simple => &*TS_MAP,
    };
    let input_chars = input.chars();
    // output_flag 记录每个字符的匹配长度和转换结果
    let mut output_flag: Vec<(usize, char)> = Vec::new();
    for (_i, c) in input_chars.enumerate() {
        output_flag.push((0, c));
    }
    if output_flag.len() == 0 {
        return "".to_string();
    }
    for (origin, target) in convert_map {
        let re = Regex::new(origin).unwrap();
        for caps in re.captures_iter(input) {
            // 3个字节表示一个字符，贪心扫描找最长匹配
            let start = caps.get(0).unwrap().start() / 3;
            let end = caps.get(0).unwrap().end() / 3;
            let caps_len = end - start;
            let target_chars = target.chars().collect::<Vec<char>>();
            for (i, ch) in target_chars.iter().enumerate() {
                if caps_len > output_flag[start + i].0 {
                    output_flag[start + i] = (caps_len, *ch);
                }
            }
        }
    }
    output_flag.iter().map(|x| x.1).collect()
}

pub fn converter(input: &str, tp: &str) -> String {
    match tp {
        "t2s" => {
            translate(input, ConverterType::Traditional2Simple)
        }
        "s2t" => {
            translate(input, ConverterType::Simple2Traditional)
        }
        _ => {
            panic!("unknown mode")
        }
    }    
}
